<template>
	<div class="register-container">
		<div class="form-wrapper">
			<h2 class="title">欢迎注册</h2>

			<van-form @submit="handleSubmit" :validate-trigger="['onChange', 'onSubmit']">
				<!-- 登录账号输入 -->
				<van-field v-model="form.account" placeholder="请输入手机号" left-icon="phone-o" class="oval-field" type="number"
					:rules="phoneRules" name="account"/>

				<van-field v-model="form.verification" name="verification" placeholder="请输入验证码" left-icon="comment-o"
					class="oval-field" :rules="codeRules">
					<template #button>
						<van-button size="small" :disabled="isCounting" @click="sendCode" native-type="button">
							{{ codeButtonText }}
						</van-button>
					</template>
				</van-field>

				<van-field v-model="form.name" placeholder="请输入您的姓名" left-icon="user-circle-o" class="oval-field"
					:rules="nameRules" name="name"/>

				<!-- 密码输入 -->
				<van-field v-model="form.password" type="password" placeholder="请设置登录密码" left-icon="lock"
					:rules="passwordRules" class="oval-field" name="password"/>

				<van-field v-model="form.confirmPassword" type="password" placeholder="请确认登录密码" left-icon="lock"
					class="oval-field" :rules="confirmPasswordRules" name="confirmPassword"/>


				<!-- 注册按钮 -->
				<van-button block type="primary" native-type="submit" class="submit-btn"  size="large">
					立即注册
				</van-button>
			</van-form>
			<div class="divider-container">
				<div class="divider-line"></div>
				<span class="divider-text" @click="$router.replace('/login')">已有账户。立即登录</span>
				<div class="divider-line"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onUnmounted,
		computed
	} from 'vue';
	import {
		useRouter
	} from 'vue-router';
	import {
		showFailToast,
		showToast,
		showSuccessToast,
		showLoadingToast
	} from 'vant';
	import {
		sendVerification,
		register
	} from '@/api/login';

	const router = useRouter()


	// 初始化空表单
	const initForm = () => ({
		account: '',//登录账号
		verification:'',//验证码
		name: '',//姓名
		password: '',//密码
		confirmPassword: ''// 确认密码
	});

	const form = ref(initForm());// 表单数据


	// 手机号验证规则
	const phoneRules = [{
		required: true,
		message: '请输入手机号'
	}, {
		pattern: /^1[3-9]\d{9}$/,
		message: '手机号格式不正确'
	}];

	const codeRules = [{
		required: true,
		message: '请填写验证码'
	}];

	const accountRules = [{
		required: true,
		message: '请输入登录账号'
	}];

	// 密码验证规则
	const passwordRules = [{
		required: true,
		message: '请输入密码'
	}, {
		pattern: /^.{6,8}$/,
		message: '密码需6-8位'
	}];

	// 二次密码验证规则
	const confirmPasswordRules = [{
		required: true,
		message: '请再次输入密码确认'
	}, {
		validator: (value) => value === form.value.password,
		message: '两次输入的密码不一致'
	}];

	const nameRules = [{
		required: true,
		message: '请输入您的姓名'
	}];


	// 验证码倒计时相关
	const countDown = ref(0);
	const isCounting = computed(() => countDown.value > 0);
	const codeButtonText = computed(() =>
		isCounting.value ? `${countDown.value}秒后重发` : '发送验证码'
	);

	let timer = null;


	// 发送验证码
	const sendCode = async () => {
		try {
			// 更严谨的手机号验证（直接使用正则验证）
			if (!/^1[3-9]\d{9}$/.test(form.value.account)) {
				showFailToast('请输入正确的手机号');
				return;
			}

			showLoadingToast({
				message: '发送中...',
				forbidClick: true
			});
			
			const account = {
				account: form.value.account
			};

			const response = await sendVerification(account);

			if (response.status === 200) {
				startCountDown();
				showSuccessToast('验证码已发送');
			} else {
				showFailToast(response.desc || '验证码发送失败');
			}
		} catch (error) {
			console.log(error)
			// 处理网络错误
			const errorMsg = error.desc || '验证码发送失败';
			showFailToast(errorMsg);
		}
	};
	// 封装倒计时逻辑
	const startCountDown = (seconds = 60) => {
		// 清理已有计时器
		if (timer) clearInterval(timer);

		countDown.value = seconds;
		timer = setInterval(() => {
			countDown.value--;
			if (countDown.value <= 0) {
				clearInterval(timer);
			}
		}, 1000);
	};

	// 组件卸载时清理定时器
	onUnmounted(() => {
		if (timer) clearInterval(timer);
	});

	// 提交注册
	const handleSubmit = async () => {
		if (form.value.password !== form.value.confirmPassword) {
			showFailToast('两次密码输入不一致');
			return;
		}

		try {
			const response = await register(form.value);
			if (response.status == 200) {
				showToast({
					type: 'success',
					message: '注册成功',
					forbidClick: true
				});
				form.value = initForm() // 清空表单
				setTimeout(() => {
					router.replace('/login') // 跳转到登录页
				}, 2000)
			} else {
				showToast({
					type: 'fail',
					message: response.desc || '注册失败',
					forbidClick: true
				});
			}
		} catch (error) {
			showToast({
				type: 'fail',
				message: error.desc || '注册失败',
				forbidClick: true
			});
		}
	};
</script>

<style lang="scss" scoped>
	.register-container {
		width: 100%;
		//position: fixed;
		//top: 0;
		//left: 0;
		//right: 0;
		//bottom: 0;
		overflow-y: auto;
		min-height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		background: linear-gradient(to bottom, #23a6d5, #23d5ab);
		/* 从上到下的蓝色渐变 */
		padding-top: 80px;
		// box-sizing: border-box;

		.divider-container {
			display: flex;
			align-items: center;
			margin: 120px 0;
		}

		.divider-line {
			flex: 1;
			height: 1px;
			background-color: #dcdfe6;
		}

		.divider-text {
			padding: 0 15px;
			color: white;
			font-size: 14px;
			cursor: pointer;
		}

		.form-wrapper {
			width: 85%;
			max-width: 400px;

			.title {
				text-align: center;
				margin-bottom: 40px;
				color: white;
				font-size: 24px;
			}

			.oval-field {
				margin-bottom: 12px;
				border-radius: 25px;
				background: #fff;
				box-shadow: 0 3px 12px rgba(58, 123, 213, 0.1);
				opacity: 0.5;
				display: flex;
				align-content: center;
				align-items: center;

				:deep(.van-field__left-icon) {
					margin-left: 15px;
					color: #3a7bd5;
				}
			}

			.sms-container {
				display: flex;
				gap: 10px;
				margin-bottom: 20px;

				.sms-input {
					flex: 1;
					border-radius: 25px;
					//background: #fff;
					opacity: .5;
					box-shadow: 0 3px 12px rgba(58, 123, 213, 0.1);

					:deep(.van-field__left-icon) {
						margin-left: 15px;
						color: #3a7bd5;
					}
				}
			}

			.sms-btn {
				border-radius: 15px;
				background: #3a7bd5;
				color: white !important;
				border: none;
				padding: 0 15px;

				&:disabled {
					background: #c8d9ff !important;
				}
			}

			.submit-btn {
				margin-top: 30px;
				border-radius: 25px;
				//background: linear-gradient(45deg, #3a7bd5, #00d2ff);
				background-color: white;
				color: #23a6d5;
				border: none;
				box-shadow: 0 4px 15px rgba(58, 123, 213, 0.2);
			}
		}
	}
</style>